package mundo.java.server;

import java.util.LinkedHashMap;
import java.util.Map;

import mundo.java.client.GreetingService;
import mundo.java.shared.FieldVerifier;
import mundo.java.shared.GreetingAction;
import mundo.java.shared.GreetingResponse;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {
	private Map<GreetingAction, GreetingResponse> messagesMap = new LinkedHashMap();
	
	public GreetingResponse greetServer(GreetingAction action) {
		// Verify that the input is valid. 
		// If the input is not valid, throw an IllegalArgumentException back to the client.
		String input = action.getTextToServer();
		if (!FieldVerifier.isValidName(input))
			throw new IllegalArgumentException("Name must be at least 4 characters long");

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		
		GreetingResponse res = new GreetingResponse(serverInfo, userAgent);
		messagesMap.put(action, res);
		return res;
	}

	@Override
	public Map<GreetingAction, GreetingResponse> list() {
		return messagesMap;
	}
}